/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package org.refunite.mobile.s60.persistence;

import org.refunite.mobile.s60.dto.ServerConfigData;
import org.refunite.mobile.s60.dto.CompletedFormData;
import org.refunite.mobile.s60.util.SecurityUtility;
import java.util.Vector;
import javax.microedition.rms.RecordEnumeration;
import javax.microedition.rms.RecordStore;

/**
 *
 * @author I040022
 */
public class PersistenceStoreProvider {
    private static final String RECORD_STORE_NAME_COLLECTED_DATA = "REFUNITED_COLLECTED_DATA";
    private static final String RECORD_STORE_NAME_CONFIGURATION = "REFUNITED_CONFIGURATION";
    private static final String RECORD_STORE_NAME_REGISTRATION_FORM = "REFUNITED_REGISTRATION_FORM";
    private static final String RECORD_STORE_NAME_LANGUAGE = "REFUNITED_FORM_LANGUAGE";
    private static final String RECORD_STORE_NAME_KEY = "REFUNITED_KEY";
    private static final String RECORD_STORE_NAME_INITV = "REFUNITED_INITV";

    public static void deleteCompletedRegistrationForm(int recordID){
        try{
            RecordStore rs = RecordStore.openRecordStore(RECORD_STORE_NAME_COLLECTED_DATA, true);
            rs.deleteRecord(recordID);
            rs.closeRecordStore();
        }catch(Exception e){
            e.printStackTrace();
        }

    }

    public static void saveCompletedRegistrationForm(String content){
        addFormToRecordStore(RECORD_STORE_NAME_COLLECTED_DATA, content);
    }

    public static Vector getCompletedRegistrationForms(){
        Vector retValue = new Vector();
        try{
            RecordStore rs = RecordStore.openRecordStore(RECORD_STORE_NAME_COLLECTED_DATA, true);
            RecordEnumeration recEnum = rs.enumerateRecords(null, null, false);
            while(recEnum.hasNextElement()){
                int recordId = recEnum.nextRecordId();
                SecurityUtility sec = new SecurityUtility();
                byte[] secFormContent = sec.decryptString(rs.getRecord(recordId));
                
                String record = new String(secFormContent, "UTF-8").trim();
                CompletedFormData form = new CompletedFormData(recordId, record);
                retValue.addElement(form);
            }
            rs.closeRecordStore();
        }catch(Exception e){
            e.printStackTrace();
        }
        return retValue;
    }
    public static int getNumOfCompletedRegistrationForms(){
        int recordStoreSize = 0;
        try{
            RecordStore rs = RecordStore.openRecordStore(RECORD_STORE_NAME_COLLECTED_DATA, false);
            recordStoreSize = rs.getNumRecords();
            rs.closeRecordStore();
        }catch(Exception e){
            e.printStackTrace();
        }
        return recordStoreSize;
    }

    public static ServerConfigData getServerConfiguration(){
        RecordStore rs = null;
        ServerConfigData retValue = null;
        try{
           rs = RecordStore.openRecordStore(RECORD_STORE_NAME_CONFIGURATION, false);
           if(rs != null && rs.getNumRecords() > 0){
               RecordEnumeration recEnum = rs.enumerateRecords(null, null, false);
               while(recEnum.hasNextElement()){
                   int recordId = recEnum.nextRecordId();
                   byte[] byteArray = rs.getRecord(recordId);
                   SecurityUtility util = new SecurityUtility();
                   byte[] decryptedContent = util.decryptString(byteArray);
                   retValue = ServerConfigData.unmarshall(decryptedContent);
               }
                rs.closeRecordStore();
            }
        }catch(Exception rse){
            rse.printStackTrace();
        }
        if(retValue == null){
            retValue = new ServerConfigData("", "", "");
        }
        return retValue;
    }

    public static void saveFormLanguage(String language){
        deleteRecordStore(RECORD_STORE_NAME_LANGUAGE);
        addToRecordStore(RECORD_STORE_NAME_LANGUAGE, new String[]{language});
    }

    public static String getFormLanguage(){
        String retValue = null;
        try{
            RecordStore rs = RecordStore.openRecordStore(RECORD_STORE_NAME_LANGUAGE, false);
            if(rs != null && rs.getNumRecords() > 0){
                RecordEnumeration recEnum = rs.enumerateRecords(null, null, false);
                while(recEnum.hasNextElement()){
                    byte[] encryptedContent = recEnum.nextRecord();
                    SecurityUtility a = new SecurityUtility();
                    retValue = new String(a.decryptString(encryptedContent)).trim();

                }
                rs.closeRecordStore();
            }
        }catch(Exception e){
            e.printStackTrace();
        }
        return retValue;
    }

    public static void saveServerConfiguration(String serverURL, String username, String password){
        // delete everything from configuration record store for easier handling
        deleteRecordStore(RECORD_STORE_NAME_CONFIGURATION);
        addToRecordStore(RECORD_STORE_NAME_CONFIGURATION, new String[]{new String(ServerConfigData.marshall(serverURL, username, password))});
    }

    public static String readFormContent(){
        String formContent = null;
        try{
            RecordStore rs = RecordStore.openRecordStore(RECORD_STORE_NAME_REGISTRATION_FORM, false);
            if(rs != null && rs.getNumRecords() > 0){
                RecordEnumeration recEnum = rs.enumerateRecords(null, null, false);
                while(recEnum.hasNextElement()){
                    SecurityUtility sec = new SecurityUtility();
                    formContent = new String(sec.decryptString(recEnum.nextRecord()),"UTF-8").trim();
                }
                rs.closeRecordStore();
            }
        }catch(Exception e){
            // do nothing
        }
        return formContent;
    }

    public static byte[] getKey(){
        byte[] content = null;
        try{
            RecordStore rs = RecordStore.openRecordStore(RECORD_STORE_NAME_KEY, false);
            if(rs != null && rs.getNumRecords() > 0){
                RecordEnumeration recEnum = rs.enumerateRecords(null, null, false);
                while(recEnum.hasNextElement()){
                    content = recEnum.nextRecord();
                }
                rs.closeRecordStore();
            }
        }catch(Exception e){
            e.printStackTrace();
        }
        return content;
    }

    public static byte[] getInitV(){
        byte[] content = null;
        try{
            RecordStore rs = RecordStore.openRecordStore(RECORD_STORE_NAME_INITV, false);
            if(rs != null && rs.getNumRecords() > 0){
                RecordEnumeration recEnum = rs.enumerateRecords(null, null, false);
                while(recEnum.hasNextElement()){
                    content = recEnum.nextRecord();
                }
                rs.closeRecordStore();
            }
        }catch(Exception e){
            e.printStackTrace();
        }
        return content;
    }

    public static void saveKey(byte[] content){
        deleteRecordStore(RECORD_STORE_NAME_KEY);
        addToRecordStore(RECORD_STORE_NAME_KEY, content, false);
    }

    public static void saveInitV(byte[] content){
        deleteRecordStore(RECORD_STORE_NAME_INITV);
        addToRecordStore(RECORD_STORE_NAME_INITV, content, false);
    }

    public static void updateFormContent(String content){
        // first delete form from store
        deleteRecordStore(RECORD_STORE_NAME_REGISTRATION_FORM);
        addFormToRecordStore(RECORD_STORE_NAME_REGISTRATION_FORM, content);
    }

    private static boolean checkRecordStoreExistence(String storeName){
        if(RecordStore.listRecordStores() != null){
            String[] recordStores = RecordStore.listRecordStores();
            if(recordStores != null && recordStores.length > 0){
                for(int i = 0; i<recordStores.length; i++){
                    String recStoreName = recordStores[i];
                    if(storeName.equalsIgnoreCase(recStoreName)){
                        return true;
                    }
                }
            }
        }
        return false;
    }
    private static void deleteRecordStore(String storeName){
        try{
            // delete only if exists
            if(checkRecordStoreExistence(storeName)){
                RecordStore.deleteRecordStore(storeName);
            }
        }catch(Exception e ){
            e.printStackTrace();
        }
    }

    private static void addFormToRecordStore(String storeName, String form){
        try{
            addToRecordStore(storeName, form.getBytes("UTF-8"), true);
        }catch(Exception e){
            
        }
    }

    private static void addToRecordStore(String storeName, String[] values){
        for(int i = 0; i < values.length; i++){
            String value = values[i];
            addToRecordStore(storeName, value.getBytes(), true);
        }
    }

    private static void addToRecordStore(String storeName, byte[] value, boolean secure){
        RecordStore rs = null;
        try{
            rs = RecordStore.openRecordStore(storeName, true);
            if(secure){
                SecurityUtility util = new SecurityUtility();
                byte[] secureValue = util.encryptString(value);
                rs.addRecord(secureValue, 0, secureValue.length);
            }else{
                rs.addRecord(value, 0, value.length);
            }
            rs.closeRecordStore();
        }catch(Exception e){
            e.printStackTrace();
        }
    }


}
